import { Component, OnInit } from '@angular/core';
import { read } from 'xlsx';

@Component({
  selector: 'app-salary',
  templateUrl: './salary.component.html',
  styleUrls: ['./salary.component.css'],
})
export class SalaryComponent implements OnInit {
  sending: boolean = true;
  fileChose: boolean = false;
  xlsxFile!: File;
  selectFileName: string = '';
  message: string = 'No Message';
  msgClass: string = 'primary';
  progress: string = '12/121';
  inputElement!: HTMLInputElement;
  constructor() {}
  showMsg(text: string, type: 'success' | 'warning' | 'error' | 'info') {
    this.message = text;
    this.msgClass = type;
  }

  handleFileChange(e: Event) {
    this.inputElement = e.target as HTMLInputElement;
    if (this.inputElement.files) {
      this.fileChose = true;
      this.selectFileName = this.inputElement.files[0].name;
      this.xlsxFile = this.inputElement.files[0];
    }
  }
  handleDeleteFile() {
    this.fileChose = false;
    this.selectFileName = '';
    if (this.inputElement) {
      this.inputElement.value = '';
    }
  }
  findMaxLine(ref: string | undefined): number {
    if (!ref) {
      return NaN;
    }
    try {
      let last = ref.split(':')[1];
      let result: number;
      for (let i = 0; i < last.length; i++) {
        let may_num = last.slice(i, last.length);
        result = parseInt(may_num);
        if (!isNaN(result)) {
          return result;
        }
      }
      return NaN;
    } catch (err) {
      console.warn('findMaxLine Error: ', err);
    } finally {
      return NaN;
    }
  }
  readXlsxFile() {
    let fileReader = new FileReader();
    fileReader.onload = (e) => {
      let data = e.target?.result;
      if (data) {
        this.checkBeforeUpload(data);
      }
    };
    fileReader.readAsArrayBuffer(this.xlsxFile);
  }
  checkBeforeUpload(data: ArrayBuffer | string): boolean {
    let xlsx = read(data, { type: 'array' });
    if (!xlsx.Sheets['公司全部']) {
      this.showMsg("没有'公司全'sheet", 'warning');
      return false;
    }
    let sheet = xlsx.Sheets['公司全部'];
    let lineNum = this.findMaxLine(sheet['!ref']);
    if (lineNum <= 2) {
      this.showMsg('文件为空', 'warning');
      return false;
    }
    return true;
  }
  handleUploadAndSend() {
    this.readXlsxFile();
  }
  ngOnInit(): void {
    window.onbeforeunload = (e: any) => {
      e.returnValue = 'Sure?';
      return 'Sure?';
    };
  }
}
